Skip to content

feat(client): Automatic Token Refresh and Authentication Recovery - #181

Merged
mckaragoz merged 13 commits into
CodeBeamOrg:devfrom
mckaragoz:AutoRefresh
Nov 29, 2026
Merged

mckaragoz merged 13 commits into
CodeBeamOrg:devfrom
mckaragoz:AutoRefresh

Conversation

@mckaragoz

@mckaragoz mckaragoz commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #111

Introduces a unified automatic token refresh and authentication recovery pipeline for UltimateAuth clients, improving session continuity and reducing the need for manual refresh handling.

The implementation supports reactive, proactive, and background refresh strategies, coordinated through a shared refresh infrastructure with concurrency control, authentication lifecycle isolation, and guarded request replay.

What's Changed

Automatic Refresh Strategies

  • Reactive Refresh: Automatically attempts token refresh after an explicit authentication recovery challenge (HTTP 401), then safely replays the original request once.
  • Proactive Refresh: Checks token expiration before authenticated requests and refreshes when the configured expiration threshold is reached.
  • Background Refresh: Automatically refreshes credentials based on JWT expiration or configured intervals, without requiring user interaction.
  • Manual & Initial Recovery: Unifies explicit refresh operations and initial authentication recovery under the same coordination pipeline.

Strategies can be configured independently through UAuthClientOptions.AutoRefresh.

Unified Refresh Coordination

  • Introduced shared refresh coordination with single-flight execution to prevent duplicate concurrent refresh requests.
  • Added authentication epochs and token generations to protect against stale refresh results.
  • Prevented outdated refresh responses from overwriting credentials after logout, account switching, or token rotation.
  • Added expiration-aware scheduling for JWTs and interval-based scheduling for opaque and cookie-only authentication.
  • Implemented rate-limit handling with Retry-After support and bounded retry backoff.

Authentication Recovery & Request Replay

  • Added recovery support for protected UltimateAuth endpoints and Resource API requests.
  • Introduced an explicit server-side authentication recovery challenge to distinguish authentication failures from ordinary endpoint errors.
  • Supports guarded, single-attempt replay for GET and supported mutation operations.
  • Validates authentication lifecycle, token generation, and credential freshness before replay.
  • Prevents replay loops and avoids treating ordinary 401, 403, or 429 responses as automatic recovery triggers.

Background Lifecycle & Reliability

  • Improved background coordinator start, stop, restart, cancellation, and disposal handling.
  • Added protection against concurrent lifecycle operations and overlapping background loops.
  • Ensured background refresh throttling is isolated by authentication epoch.
  • Preserved explicit refresh and recovery behavior independently from automatic refresh backoff.

Client & Server Integration

  • Updated Blazor request transports and JavaScript interop to preserve authentication recovery and rate-limit metadata.
  • Integrated refresh coordination across client service domains and Resource API requests.
  • Updated protected endpoint handling and authentication challenge responses.
  • Kept refresh-related services scoped to prevent authentication state sharing between client scopes.

Configuration

options.AutoRefresh.Reactive = true;
options.AutoRefresh.Proactive = true;
options.AutoRefresh.Background = true;

options.AutoRefresh.RefreshBeforeExpiration = TimeSpan.FromMinutes(1);

options.AutoRefresh.Interval = TimeSpan.FromMinutes(5);

Reactive and proactive refresh are enabled by default. Background refresh is controlled independently.

Testing

Expanded unit, integration, and JavaScript test coverage for:

  • Concurrent refresh execution and single-flight coordination
  • Reactive recovery and proactive refresh scheduling
  • JWT expiration and token rotation boundaries
  • Authentication epoch and generation isolation
  • Safe replay of protected requests
  • Rate limiting, retry backoff, and failure handling
  • Background coordinator lifecycle and disposal
  • Dependency injection scope isolation
  • Client state consistency and transport behavior

Notes

  • Automatic refresh improves session continuity but does not guarantee that a session can always be renewed.
  • Request replay requires an explicit authentication recovery challenge and an eligible replacement credential.
  • Multi-tab refresh coordination remains outside the scope of this PR.

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.40701% with 139 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.17%. Comparing base (e6bd9b3) to head (21ef5b9).
⚠️ Report is 1 commits behind head on dev.

Files with missing lines Patch % Lines
...Client.Blazor/Infrastructure/SessionCoordinator.cs 78.71% 32 Missing and 11 partials ⚠️
...UltimateAuth.Client/AuthState/UAuthStateManager.cs 69.31% 16 Missing and 11 partials ⚠️
...Auth.Client/Infrastructure/UAuthRefreshExecutor.cs 91.54% 7 Missing and 10 partials ⚠️
...zor/Infrastructure/UAuthRecoveringRequestClient.cs 83.09% 9 Missing and 3 partials ⚠️
...lazor/Infrastructure/UAuthResourceRequestClient.cs 88.88% 8 Missing and 4 partials ⚠️
...Client.Blazor/Infrastructure/UAuthRequestClient.cs 75.00% 5 Missing and 3 partials ⚠️
...h.Client/Infrastructure/UAuthRefreshCoordinator.cs 91.25% 4 Missing and 3 partials ⚠️
...Auth.Server/Auth/Context/AuthFlowEndpointFilter.cs 70.00% 0 Missing and 3 partials ⚠️
...am.UltimateAuth.Client/Services/UAuthUserClient.cs 83.33% 3 Missing ⚠️
...spNetCore/UAuthStatusAuthorizationResultHandler.cs 80.00% 0 Missing and 2 partials ⚠️
... and 4 more
Additional details and impacted files
@@            Coverage Diff             @@
##              dev     #181      +/-   ##
==========================================
+ Coverage   88.05%   88.17%   +0.11%     
==========================================
  Files         615      626      +11     
  Lines       20864    21799     +935     
  Branches     2529     2675     +146     
==========================================
+ Hits        18372    19221     +849     
- Misses       1601     1645      +44     
- Partials      891      933      +42     
Flag Coverage Δ
framework 88.17% <88.40%> (+0.11%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@mckaragoz
mckaragoz merged commit aa24841 into CodeBeamOrg:dev Nov 29, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Resource Request Recovery & Retry

1 participant